package cn.zl.ymcc.test;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        try {
            // 1. 设置参数
            Factory.setOptions(getOptions());

            // 2. 发起API调用
            String outTradeNo = "TEST" + System.currentTimeMillis();
            System.out.println("订单号: " + outTradeNo);
            System.err.println(outTradeNo);

            AlipayTradePagePayResponse response = Factory.Payment.Page()
                    .pay("测试商品", outTradeNo, "0.01", "https://www.baidu.com");

            // 3. 处理响应
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");

                // 将返回的HTML表单保存到文件
                String htmlContent = response.getBody();
                saveHtmlToFile(htmlContent, "alipay_payment.html");

                System.out.println("支付页面已保存为: alipay_payment.html");
                System.out.println("请用浏览器打开此文件进行支付测试");

            } else {
                System.err.println("调用失败: " );
            }

        } catch (Exception e) {
            System.err.println("调用遭遇异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void saveHtmlToFile(String htmlContent, String filename) {
        try {
            String filePath = Paths.get(System.getProperty("user.dir"), filename).toString();
            FileWriter writer = new FileWriter(filePath);
            writer.write(htmlContent);
            writer.close();
            System.out.println("文件保存路径: " + filePath);
        } catch (IOException e) {
            System.err.println("保存HTML文件失败: " + e.getMessage());
        }
    }

    private static Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi-sandbox.dl.alipaydev.com";
        config.signType = "RSA2";
        config.appId = "9021000157633142";
        config.merchantPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCgrkOAahDv98dv6f/vOtlWVlL6GX12Furd5i7Y6bCkf49KHsqleSbTo/z9OYhG8NtPIAnYdcU2Xt0v4Q+85l7I9lMYbpMapTPaySYDwC+GmPYFiE9xpYHS0GvGOcc+bua+yWJvD0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